//二次封装axios
import axios, { AxiosResponse, InternalAxiosRequestConfig, AxiosRequestConfig } from 'axios'
 
//权限跳转
interface AxiosRequestConfigExtended extends AxiosRequestConfig {
  retry: number
  retryDelay: number
}

interface ApiError extends Error {
  response: AxiosResponse;
  config: AxiosResponse & { url: string };
}

const service = axios.create({
  baseURL: '', // 基本路径
  retry: 2, // 重试次数
  retryDelay: 1000, // 重发等待时间
  timeout: 180 * 1000
} as AxiosRequestConfigExtended)

service.interceptors.request.use(
  async (config: InternalAxiosRequestConfig) => {
    // 传参baseURL的情况
    if (config.data?.baseUrl) {
      config.baseURL = config.data.baseUrl
    }

    return config
  },
  (error: ApiError) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data
  },
  async (error: any) => {
    if (!error.response) {
      if (error.code === 'ERR_CANCELED') {
        return Promise.resolve('请求被取消')
      }
      return Promise.reject(error)
    }
    
    return Promise.reject(error)
  }
)

export { service }
  
